import { comsType, CHECKED } from '../../constants/form';
import _ from 'lodash';
const { FORM_HEADER, FORM_FOOTER, FOOTER } = comsType;

// 组件props配置 转成view配置
export const propsComToViewCom = component => {
  const com = { ...component };
  const { title, hidden } = com.config;

  com.rules = [];
  com.name = title;
  com.visible = true; // 用于控制组件显隐，如字段显示规则

  if (hidden && Number(hidden) === 1) { //隐藏字段不做渲染
    com.visible = false;
  }

  if ('defaultValue' in com.config) {
    com.value = com.config.defaultValue;
  }

  return com;
}

export const getViewableComponent = com => {
  const isInFormBody = ![FORM_HEADER, FORM_FOOTER, FOOTER].includes(com.type);
  const isNotSubComponent = !com.pid;

  return isNotSubComponent && isInFormBody;
};

export const split = com => {
  const { config } = com;

  return config.complex.filter(key => {
    return CHECKED === config[key].required
  }).map(key => {
    const subCom = config[key];

    subCom.config.required = config.required;
    subCom.config.defaultValue = subCom.value;

    return {
      ...subCom,
      pid: com.uuid
    };
  });
}

export const convertToViewableComs = (coms, subComsMap) => {
  return coms.filter(com => getViewableComponent(com))
    .map(com => {
      const { coms } = com.config;

      if (coms) {
        com.config.coms = coms.map(subComId => subComsMap[subComId]);
      }

      return com;
    });
}

export const getSize = (size, hasSpace) => {
  const units = ['KB', 'MB'];
  let unit = units[0];
  let i = 0;

  do {
    size = Math.ceil(size / 1024 * 10) / 10;
    unit = units[i++];
  } while (size >= 1024)

  return `${size}${hasSpace ? ' ' : ''}${unit}`;
}

export function getWidthPct(cellspan, totalspan) {
  return 1 / totalspan * cellspan;
}

export function getWidthPX(width, percentage) {
  return `${width * percentage}px`;
}

export const toViewData = (config) => {
  let { coms, defaultValue, defaultRowValue } = config;

  if (coms) {
    coms = coms.map(com => com && propsComToViewCom(com));
    defaultRowValue = coms.map(com => com && com.value);
    defaultValue = [_.cloneDeep(defaultRowValue)];
  }

  return {
    ...config,
    coms,
    defaultValue,
    defaultRowValue,
    errors: [[]],
  };
}